import remoteSearchProductInput from '../../../order/components/remote-search-product-input';
import remoteSearchTechnologyOrderInput from '../../../order/components/remote-search-technology-order-input';
import { productionPrdNoticeMachineChangeBatchCreateAndOpen } from '../../../../../api/production/xsNotice';
import { formatTime } from '../../../../../utils/jk/jk-tool';
import { mathJsDiv } from '../../../../../utils/jk/jk-cals';
import remoteSearchBatchCodeInput from '../../../qhPrd/productConfigCotton/components/remote-search-batch-code-input';
import checkboxPopover from '../../../order/components/form-box/checkbox-popover';
import { spinSpecSheetGet } from '../../../../../api/technology/order';
import { openStateList } from '../../../../../utils/jk/status-option-list';
import openCloseRenovate from '../../../productOpenCloseMachine/components/open-close-renovate';
import permissionMixin from '../../../../../mixins/permission-mixin';
import getTubeColor from '../../../foreSpinPrd/foreSpinningPlan/components/form-box/get-tube-color';
import handlerCache from '../../../../../mixins/handler-cache';
import machineStateBar from '../../../productionNoticeOrder/components/machine-state-bar';
import technologyNoticeBar from '../../../productionNoticeOrder/components/technology-notice-bar';
import selectMachineGanttDialog from '../../../productionNoticeOrder/components/select-machine-gantt-dialog';
import noticeStateBar from '../../../productionNoticeOrder/components/notice-state-bar';
import noticeMachineList from './notice-machine-list';
import { productionPrdNoticeMachineChangeGetMachineDataList } from '../../../../../api/production/xsOpen';
import initFormData from '../../../productionNoticeOrder/components/form-box/init-form-data';
export default {
	components: {
		noticeMachineList,
		noticeStateBar,
		selectMachineGanttDialog,
		machineStateBar,
		technologyNoticeBar, checkboxPopover, remoteSearchProductInput, remoteSearchBatchCodeInput, remoteSearchTechnologyOrderInput
	},
	mixins: [initFormData, openCloseRenovate, permissionMixin, getTubeColor, handlerCache],
	props: {
		formData: {
			type: Object,
			default() {
				return {};
			}
		},
		dialogState: {
			type: Boolean,
			default: false
		},
		pageType: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			checkMachineData: [],
			showContentLoading: false,
			openStateList: openStateList,
			selectMachineGanttDialogState: false,
			confirmBtnLoading: false,
			saveDialogState: false,
			detailDataMachineList: [],
			showDialog: false
		};
	},
	methods: {
		onDailyYieldChange(e) {
			this.ruleForm.prdNoticeMachineList.forEach(x => {
				if (!x.specSheet.code) {
					if (x.openingState !== 4) {
						x.specSheet.dailyYield = e;
						x.dailyYield = e;
					}
				}
			});
		},
		onAddMachineBtn() {
			// 除了已了机，不允许重复添加
			this.checkMachineData = this.ruleForm.prdNoticeMachineList ? this.ruleForm.prdNoticeMachineList.filter(x => x.openingState !== 4) : [];
			this.selectMachineGanttDialogState = true;
		},
		onConfirmBtnOfSelectMachineGanttDialog(arr) {
			this.insertMachineData(arr);
			this.selectMachineGanttDialogState = false;
		},
		insertMachineData(arr) {
			const technologyInfo = JSON.parse(JSON.stringify(this.technologyOrderInfo));
			// 没有工艺单时，默认定量和台日单产
			if (!this.ruleForm.specSheetId) {
				technologyInfo.dailyYield = this.ruleForm.dailyYield;
				technologyInfo.meters = this.ruleForm.meters;
				technologyInfo.gramWeight = this.ruleForm.gramWeight;
			}
			arr.forEach(x => {
				technologyInfo.gramWeight = this.ruleForm.productOrder.gramWeight;
				technologyInfo.meters = this.ruleForm.productOrder.meters;
				this.ruleForm.prdNoticeMachineList.push({
					startSystemTime: formatTime(Date.now()),
					machineId: x.id,
					machineCode: x.code,
					machineName: x.name,
					machineModelId: x.machineModelId,
					machineModelCode: x.machineModelCode,
					machineModelName: x.machineModelName,
					productionQty: null,
					productionDays: null,
					subPlanEndDate: '',
					dailyYield: this.ruleForm.dailyYield,
					processId: x.processId,
					processCode: x.processCode,
					processName: x.processName,
					specSheet: technologyInfo,
					openingState: 0,
					inputTubeColorList: this.ruleForm.inputTubeColorList ? JSON.parse(JSON.stringify(this.ruleForm.inputTubeColorList)) : [],
					outputTubeColorList: [],
					// 采集的表量信息
					startElectricEnergy: x.startElectricEnergy,
					startSystemElectricEnergy: x.startSystemElectricEnergy,
					startOutput: x.startOutput,
					startSystemOutput: x.startSystemOutput,
					lastEndOutput: x.lastEndOutput,
					lastEndElectricEnergy: x.lastEndElectricEnergy,
					openSpinCount: x.openSpinCount,
					usedSpinCount: x.usedSpinCount,
					spinCount: x.spinCount,
					startOutputKg: x.startOutputKg,
					startSystemOutputKg: x.startSystemOutputKg
				});
			});
		},
		onSelectTechnologyOrderChange(e) {
			this.clearFormItemVal('technology');
			if (e && Object.keys(e).length) {
				this.$set(this.ruleForm, 'specSheetId', e.id);
				this.$set(this.ruleForm, 'specSheetCode', e.code);
				this.$set(this.ruleForm, 'machineModelId', e.machineModelId);
				this.$set(this.ruleForm, 'machineModelCode', e.machineModelCode);
				this.$set(this.ruleForm, 'machineModelName', e.machineModelName);
				this.$set(this.ruleForm, 'dailyYield', e.dailyYield);
				this.$set(this.ruleForm, 'moistureRegain', e.moistureRegain);
				this.$set(this.ruleForm, 'efficiencyPercent', e.efficiencyPercent);
				this.$set(this.ruleForm, 'gramWeight', e.gramWeight);
				this.$set(this.ruleForm, 'meters', e.meters);
				this.ruleForm.prdNoticeMachineList.forEach(x => {
					this.$set(x, 'dailyYield', e.dailyYield);
					this.$set(x, 'specSheetId', e.id);
					this.$set(x, 'specSheetCode', e.code);
					this.$set(x, 'specSheet', e);
					if (x.productionQty && x.dailyYield && x.subPlanStartDate) {
						const days = Math.ceil(mathJsDiv(x.productionQty, e.dailyYield));
						this.$set(x, 'productionDays', days);
					}
				});
				this.getTechnologyOrderDetailRequest(e.id);
			} else {
				this.$set(this.ruleForm, 'specSheetId', null);
				this.$set(this.ruleForm, 'specSheetCode', '');
				this.$set(this.ruleForm, 'machineModelId', null);
				this.$set(this.ruleForm, 'machineModelCode', '');
				this.$set(this.ruleForm, 'machineModelName', '');
				this.$set(this.ruleForm, 'dailyYield', null);
				this.$set(this.ruleForm, 'moistureRegain', null);
				this.$set(this.ruleForm, 'efficiencyPercent', null);
				this.$set(this.ruleForm, 'gramWeight', null);
				this.$set(this.ruleForm, 'gramWeight', null);
			}
		},
		getTechnologyOrderDetailRequest(id) {
			return spinSpecSheetGet({ id }).then(res => {
				if (res.data.status === 200) {
					this.technologyOrderInfo = res.data.res;
					this.technologyOrderInfo.specSheetParamList.map(x => {
						x.val = x.dataType === 1 ? Number(x.val) : x.val;
						x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
						x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
						return x;
					});
				}
			});
		},
		onVisibleChangeOfSelectMachineGanttDialog(e) {
			this.selectMachineGanttDialogState = e;
		},
		onSelectProductChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchId', null);
				this.$set(this.ruleForm, 'batchCode', '');
				this.$set(this.ruleForm, 'productId', e.id);
				this.$set(this.ruleForm, 'productCode', e.code);
				this.$set(this.ruleForm, 'productName', e.name);
				this.$set(this.ruleForm, 'productModels', e.models);
				this.$set(this.ruleForm, 'unitId', e.unitId);
				this.$set(this.ruleForm, 'unitCode', e.unitCode);
				this.$set(this.ruleForm, 'unitName', e.unitName);
			}
		},
		onSelectBatchChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchId', e.id);
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
			}
		},
		onSelectBatchCodeChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
			}
		},
		setDependentDataOfForm() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.prdNoticeMachineList = this.ruleForm.prdNoticeMachineList.map(x => x);
			params.machineQty = params.prdNoticeMachineList.length;
			delete params.productOrderBatchItem;
			return params;
		},
		onConfirmBtn() {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					if (this.ruleForm.prdNoticeMachineList && this.ruleForm.prdNoticeMachineList.length) {
						this.createAndUpdateRequest();
					} else {
						this.$tipsBar(this, 'custom', 'warning', '机台不能为空!');
					}
				} else {
					this.$tipsBar(this, 'custom', 'warning', '必填项未填写完整!');
				}
			});
		},
		createAndUpdateRequest() {
			this.confirmBtnLoading = true;
			productionPrdNoticeMachineChangeBatchCreateAndOpen(this.setDependentDataOfForm()).then(res => {
				this.confirmBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.$emit('on-confirm');
				}
			});
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		showLoading(e) {
			this.showContentLoading = e;
		},
		onToggleColorChange(data, key) {
			this.ruleForm.prdNoticeMachineList.forEach(x => {
				this.$set(x, key, data);
			});
		},
		onGramWeightChange(data, key) {
			this.ruleForm.prdNoticeMachineList.forEach(x => {
				if (x.openingState !== 4) {
					this.$set(x, key, data);
					this.$set(x.specSheet, key, data);
				}
			});
		},
		// 获取指定机台采集的仪表数据
		getGatherMachineDataRequest() {
			if (this.formData.machineList && this.formData.machineList.length) {
				return productionPrdNoticeMachineChangeGetMachineDataList({
					machineIds: this.formData.machineList.map(x => x.machineId),
					selectDateTime: formatTime(Date.now())
				}).then(res => {
					if (res.data.status === 200) {
						let machineData = [];
						if (this.formData.machineList) {
							machineData = this.formData && this.formData.machineList ? JSON.parse(JSON.stringify(this.formData.machineList)).map(x => {
								return {
									id: x.machineId,
									code: x.machineCode,
									name: x.machineName,
									processId: x.processId,
									processCode: x.processCode,
									processName: x.processName,
									startElectricEnergy: 0,
									startSystemElectricEnergy: 0,
									startOutput: 0,
									startSystemOutput: 0,
									lastEndOutput: 0,
									lastEndElectricEnergy: 0,
									openSpinCount: 0,
									usedSpinCount: 0,
									spinCount: 0,
									startOutputKg: 0,
									startSystemOutputKg: 0
								};
							}) : [];
						}

						const resData = res.data.res || [];
						machineData.forEach(x => {
							resData.forEach(k => {
								if (x.id === k.machineId) {
									// 开台能耗表数，默认等于采集到的实时能耗
									this.$set(x, 'startElectricEnergy', k.currentElectricEnergy);
									this.$set(x, 'startSystemElectricEnergy', k.currentElectricEnergy);
									// 开台产量表数，默认等于采集到的实时产量
									this.$set(x, 'startOutput', k.currentOutput);
									this.$set(x, 'startSystemOutput', k.currentOutput);
									// 上次的产量和能耗
									this.$set(x, 'lastEndOutput', k.lastEndOutput);
									this.$set(x, 'lastEndElectricEnergy', k.lastEndElectricEnergy);

									this.$set(x, 'openSpinCount', k.spinCount - k.usedSpinCount);
									this.$set(x, 'usedSpinCount', k.usedSpinCount);
									this.$set(x, 'spinCount', k.spinCount);

									this.$set(x, 'startOutputKg', k.currentOutputKg);
									this.$set(x, 'startSystemOutputKg', k.currentOutputKg);
								}
							});
						});
						// 放入机台
						this.insertMachineData(machineData);
					}
				});
			}
		},
		async getDependentData() {
			this.showLoading(true);
			this.$set(this.ruleForm, 'workshopId', this.formData.workshopId);
			this.$set(this.ruleForm, 'workshopCode', this.formData.workshopCode);
			this.$set(this.ruleForm, 'workshopName', this.formData.workshopName);
			this.$set(this.ruleForm, 'processId', this.formData.processId);
			this.$set(this.ruleForm, 'processCode', this.formData.processCode);
			this.$set(this.ruleForm, 'processName', this.formData.processName);

			await this.getGatherMachineDataRequest();
			if (this.getColorInfoByProcess(this.ruleForm.processCode)) await this.getInputColorListRequest(this.getColorInfoByProcess(this.ruleForm.processCode).inputTypeCode);
			if (this.getColorInfoByProcess(this.ruleForm.processCode)) await this.getOutColorListRequest(this.getColorInfoByProcess(this.ruleForm.processCode).outTypeCode);
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			this.showLoading(false);
		},
		clearCacheMethod() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	},
	watch: {
		dialogState(newVal) {
			if (newVal) {
				this.ruleForm.prdNoticeMachineList = [];
				this.getDependentData();
			}
			this.showDialog = newVal;
		}
	}
};
